package com.lyncs.ods.modules.share;

import com.alibaba.fastjson.JSONValidator;
import com.lyncs.ods.modules.share.enums.ShareTypeEnum;
import com.lyncs.ods.modules.share.strategy.ShareStrategy;
import com.lyncs.ods.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author alex
 * @date 2022/4/21 22:15
 * @description
 */
@Slf4j
public class ShareStrategyFactory {

    private static final Map<String, ShareStrategy> EXE_MAP;

    static {
        EXE_MAP = Arrays.stream(ShareTypeEnum.values()).collect(Collectors.toMap(ShareTypeEnum::getKey, e -> (ShareStrategy) SpringUtils.getBean(e.getStrategyName())));
    }

    public static Object exec(String type, String key) {
        try {
            if (StringUtils.isAnyEmpty(type, key)) {
                log.error("invalid type or key,type:{},key:{}", type, key);
                return null;
            }
            return getPullTaskExecutor(type).exec(key);
        } catch (Exception e) {
            log.error("handle share msg error", e);
        }
        return null;
    }

    /**
     * 获取执行器
     *
     * @param key key
     * @return shareStrategy
     */
    private static ShareStrategy getPullTaskExecutor(String key) {
        var shareStrategy = EXE_MAP.get(key);
        if (shareStrategy == null) {
            var msg = "no strategy found for key:" + key;
            log.error(msg);
            throw new RuntimeException(msg);
        }
        return shareStrategy;
    }
}
